using GEM.Application.Common;
using GEM.Application.Contracts.AI;
using GEM.Infrastructure.AI.Models;
using Microsoft.Extensions.Options;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;

namespace GEM.Infrastructure.AI.Services;

public class DeepseekService : IAIService
{
    private readonly HttpClient _httpClient;
    private readonly DeepseekSettings _settings;

    public DeepseekService(HttpClient httpClient, IOptions<DeepseekSettings> settings)
    {
        _httpClient = httpClient;
        _settings = settings.Value;

        _httpClient.BaseAddress = new Uri(_settings.BaseUrl);
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_settings.ApiKey}");
    }

    public async Task<dynamic> ChatAsync(string message)
    {
        if (string.IsNullOrEmpty(message))
        {
            return ApiResponse<string>.Fail(5001, "消息内容不能为空");
        }

        try
        {
            var request = new
            {
                model = _settings.Model,
                messages = new[]
                {
                    new { role = "user", content = message }
                },
                max_tokens = _settings.MaxTokens,
                temperature = _settings.Temperature,
                stream = true
            };

            var response = await _httpClient.PostAsJsonAsync("/v1/chat/completions", request);
            if (!response.IsSuccessStatusCode)
            {
                return ApiResponse<string>.Fail(5002, "AI服务调用失败");
            }

            using var stream = await response.Content.ReadAsStreamAsync();
            using var reader = new StreamReader(stream);
            var fullResponse = new StringBuilder();

            while (!reader.EndOfStream)
            {
                var line = await reader.ReadLineAsync();
                if (line == null)
                {
                    continue;
                }
                if (!line.StartsWith("data: "))
                {
                    continue;
                }

                var jsonData = line.Substring(6); // 去掉 "data: " 前缀
                if (jsonData == "[DONE]")
                {
                    break;
                }

                try
                {
                    var streamResponse = JsonSerializer.Deserialize<DeepseekResponse>(jsonData);
                    var choice = streamResponse?.Choices != null && streamResponse.Choices.Length > 0
                        ? streamResponse.Choices[0]
                        : null;
                    var content = choice?.Delta?.Content;
                    if (!string.IsNullOrEmpty(content))
                    {
                        fullResponse.Append(content);
                    }
                }
                catch (JsonException)
                {
                    continue;
                }
            }

            var aiResponse = fullResponse.ToString();
            if (string.IsNullOrEmpty(aiResponse))
            {
                return ApiResponse<string>.Fail(5003, "AI响应内容为空");
            }

            return ApiResponse<string>.Success(aiResponse);
        }
        catch (Exception ex)
        {
            return ApiResponse<string>.Fail(5000, $"AI对话异常: {ex.Message}");
        }
    }

    public async IAsyncEnumerable<string> ChatStreamAsync(string message)
    {
        if (string.IsNullOrEmpty(message))
        {
            yield return "消息内容不能为空";
            yield break;
        }

        var request = new
        {
            model = _settings.Model,
            messages = new[]
            {
                new { role = "user", content = message }
            },
            max_tokens = _settings.MaxTokens,
            temperature = _settings.Temperature,
            stream = true
        };

        var response = await _httpClient.PostAsJsonAsync("/v1/chat/completions", request);
        if (!response.IsSuccessStatusCode)
        {
            yield return "AI服务调用失败";
            yield break;
        }

        using var stream = await response.Content.ReadAsStreamAsync();
        using var reader = new StreamReader(stream);

        while (!reader.EndOfStream)
        {
            var line = await reader.ReadLineAsync();
            if (line == null)
            {
                continue;
            }
            if (!line.StartsWith("data: "))
            {
                continue;
            }

            var jsonData = line.Substring(6); // 去掉 "data: " 前缀
            if (jsonData == "[DONE]")
            {
                break;
            }

            var streamResponse = JsonSerializer.Deserialize<DeepseekResponse>(jsonData);
            var choice = streamResponse?.Choices != null && streamResponse.Choices.Length > 0
                ? streamResponse.Choices[0]
                : null;
            var content = choice?.Delta?.Content;
            if (!string.IsNullOrEmpty(content))
            {
                yield return content;
            }
        }
    }
}